#!/bin/bash
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash build.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || "$1" = "/" ]] && echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || "$2" = "/" ]] && echo "请输入正确的安装路径" && exit 1

create_dir() {
    local path=$1
    [[ "$path" =~ .*/$ ]] && path=${path%/*}
    if [[ ! -d "$path" && ! -f "$path" ]]; then mkdir -p "$path"; else path=$path$(date "+%y%m%d%H%M%S") && mkdir -p "$path"; fi
    echo "$path"
}

buildpath=$(create_dir "$1")
installpath=$(create_dir "$2")

yum install -y m4 environment-modules systemd-devel --nogpgcheck
source /etc/profile
module purge

set -e
dep_dir="dependency"
bash $dep_dir/bisheng-compiler-2.1.0.sh "$buildpath" "$installpath"
module use "$installpath"/bisheng-compiler-2.1.0
module load "$installpath"/bisheng-compiler-2.1.0/bisheng_modulefiles

bash $dep_dir/hmpi-1.1.1.sh "$buildpath" "$installpath"
module use "$installpath"/hmpi-1.1.1
module load "$installpath"/hmpi-1.1.1/hmpi_modulefiles

bash $dep_dir/miniconda-py38_4.11.0-devel.sh "$buildpath" "$installpath"
module use "$installpath"/miniconda3
module load "$installpath"/miniconda3/miniconda_py38_modulefiles

bash $dep_dir/openblas-0.3.18.sh "$buildpath" "$installpath"
bash $dep_dir/lapack-3.8.0.sh "$buildpath" "$installpath"
module use "$installpath"/openblas
module load "$installpath"/openblas/OpenBLAS-0.3.18_modulefiles

bash ambertools-21.sh "$buildpath" "$installpath"

mkdir -p pkg/ambertools-21-hpc && cp -r "$installpath"/* pkg/ambertools-21-hpc/
cat >"pkg/ambertools-21-hpc/run.sh" <<EOF
#!/bin/bash
yum install -y m4 environment-modules systemd-devel cmake csh time patch libatomic perl perl-Data-Dumper \\
autoconf automake libtool numactl binutils valgrind zlib-devel flex wget tar libatomic zlib-devel gcc-c++ git bison bzip2 bzip2-devel libXt-devel libXext-devel libX11-devel libICE-devel libSM-devel
source /etc/profile &> /dev/null 
current_dir=\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" &> /dev/null && pwd)
source \$current_dir/ambertools21/amber.sh
for d in \$(ls \$current_dir)
do
    [[ ! \$d =~ "amber" && ! -f "\$current_dir/\$d" ]] && cd \$current_dir/\$d && module use \$(pwd) && module load \$(pwd)/*modulefiles
done
cd \$current_dir
[[ ! -d "$installpath/hmpi-1.1.1" ]] && mkdir -p $installpath/hmpi-1.1.1 && cp -r \$current_dir/hmpi-1.1.1/* $installpath/hmpi-1.1.1/
EOF
cd pkg/ && tar zcvf ambertools-21-hpc.tar.gz ambertools-21-hpc

rm -rf "$buildpath" "$installpath"
